import json
from fastapi import APIRouter,HTTPException,Request
from fastapi.templating import Jinja2Templates
from neo4j import getGraph,getAllNameNode,getListItem,getRelation,getEventType
from jinja2 import Environment, FileSystemLoader
from filter import list2Json
from typing import Any
env = Environment(loader=FileSystemLoader("./templates"))
env.filters["list2Json"] = list2Json
router = APIRouter()
templates = Jinja2Templates(directory="templates")
templates.env = env

names = getAllNameNode()
graph = getGraph(names)
@router.get("/name")
async def get_name(request: Request):
    data = getListItem(graph,"事故名称")
    return templates.TemplateResponse(request,name="list.html",context={"items":data,"title":"事故名称索引","prefix":"name"})
    # return {"name":data,"reqest":request.url.path}

@router.get("/name/{nid}")
async def get_name_id(request:Request ,nid:str):
    data = getRelation(graph,("事故名称",nid))
    if nid=="all":
        nid ="事故名称检索全量"
    return templates.TemplateResponse(request,name="graph.html",context={"nodes":data[0],"rels":data[1],"c":data[2],"title":nid})    

@router.get("/site")
async def get_site(request: Request):
    data = getListItem(graph,"发生地点")
    return templates.TemplateResponse(request,name="list.html",context={"items":data,"title":"发生地点索引","prefix":"site"})
@router.get("/site/{sid}")
async def get_site_id(request:Request,sid:str):
    data = getRelation(graph,("发生地点",sid))
    if sid=="all":
        sid ="发生地点检索全量"
    return templates.TemplateResponse(request,name="graph.html",context={"nodes":data[0],"rels":data[1],"c":data[2],"title":sid}) 
@router.get("/time")
async def get_time(request: Request):
    data = getListItem(graph,"发生时间")
    return templates.TemplateResponse(request,name="list.html",context={"items":data,"title":"发生时间索引","prefix":"time"})

@router.get("/time/{tid}")
async def get_time_id(request:Request,tid:str):
    data = getRelation(graph,("发生时间",tid))
    if tid=="all":
        tid ="发生时间检索全量"
    return templates.TemplateResponse(request,name="graph.html",context={"nodes":data[0],"rels":data[1],"c":data[2],"title":tid})

@router.get("/")
async def get_index(request: Request):
    data = [("name","事故名称"),("time","发生时间"),("site","发生地点")]
    return templates.TemplateResponse(request,name="index.html",context={"items":data,"title":"事故知识图谱可视化"})

@router.get("/etype")
async def get_etype(request: Request):
    data = getEventType(graph)
    center = {"name":"事故类型","symbolSize": 70,"category":0}
    nodes = [center]
    rels = []
    for k,v in data.items():
        nodes.append({"name":k,"des":"事故具体类型","symbolSize": 50,"category":1})
        rels.append({"source":center["name"],"target":k,"des":"包含"})
        for i in v:
            tmp = {"name":i["name"],"symbolSize":40,"category":2,"des":""}
            nodes.append(tmp)
            rels.append({"source":k,"target":tmp["name"],"des":"包含"})

        
    c = ["事故类型","事故具体类型","事故实例"]
    return templates.TemplateResponse(request,name="graph.html",context={"nodes":nodes,"rels":rels,"c":c,"title":"事故类型"})


@router.get("/fake")
async def get_fake(request: Request):
    c = []
    nodes: list[dict[str, Any]]= [{"name":"作业人员","des":r"从业要求:1.具有工民建及建筑类相关专业毕业，中专以上学历；2.持职业资格证书；3.熟悉质量验收评定标准，项目施工管理，安全文明施工规范；4.熟悉相关技术、验收标准、工作流程安排、工艺重点及工序衔接；5.具备较强的施工组织、协调和沟通能力。","symbolSize": 70,"category":0}]
    nodes.append({"name":"经济损失","desc":"直接经济损失约140万元","symbolSize": 50,"category":1}) # type: ignore
    nodes.append({"name":"事故名称","des":"阳春市“12·11”阳阳铁路桥梁侧翻"})
    nodes.append({"name":"具体项目","des":"中铁(阳江)铁路有限公司负责招标，中铁二十三局集团第二工程有限公司中标的项目"})
    nodes.append({"name":"施工单位","des":"中铁二十三局集团第二工程有限公司"})
    nodes.append({"name":"事故后果","des":"7人受伤，1人死亡"})
    nodes.append({"name":"管理条例","des":"《普速铁路工务安全规则》"})
    nodes.append({"name":"法律法规","des":"《中华人民共和国安全生产法》"})
    nodes.append({"name":"发生时间","des":"2015年12月11日9时20分"})
    nodes.append({"name":"事故地点","des":"阳阳铁路阳春段K19+244处12号桥(岗美中桥)"})
    nodes.append({"name":"事故性质","des":"生产安全责任事故"})
    for idx,n in enumerate(nodes):
        if idx !=0:

            n["category"] = idx
            n["symbolSize"]= 50
        c.append(n["name"])
    rels = [{"source":"作业人员","target":"经济损失","des":"造成"},
    {"source":"作业人员","target":"具体项目","des":"参与了"},
    {"source":"施工单位","target":"具体项目","des":"负责"},
    {"source":"作业人员","target":"事故后果","des":"造成了"},
    {"source":"作业人员","target":"管理条例","des":"违反了"},
    {"source":"管理条例","target":"具体项目","des":"依据条例指导"},
    {"source":"法律法规","target":"事故名称","des":"依据法律指导"},
    {"source":"事故名称","target":"具体项目","des":"发生在某项目"},
    {"source":"事故名称","target":"发生时间","des":"发生在某时间"},
    {"source":"事故名称","target":"事故地点","des":"发生在某地点"},
    {"source":"事故名称","target":"事故性质","des":"属于"},
    {"source":"作业人员","target":"施工单位","des":"属于"},
    {"source":"作业人员","target":"法律法规","des":"触犯了"},
    ]

    return templates.TemplateResponse(request,name="graph.html",context={"nodes":nodes,"rels":rels,"c":c,"title":"安全实例"})